import QtQuick 2.0

import '../js/statics.js' as Statics
import '../js/utils.js' as Utils

Rectangle{
  id: root

  signal finished(var p)
  signal canceld()

  // helper functions
  function finClickedHandler() {
    // check if date is valid
    var str = dateInput.text.replace(" ", "T");
    if(!Utils.re.test(str))
      return cancelFinish();
    var parsed = Utils.parseDatestring(str);
    var month2day = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if(parsed.month > 12)
      return cancelFinish();
    if(parsed.day > parseInt(month2day[parsed.month]))
      return cancelFinish();
    if(parsed.hours > 23 || parsed.minutes > 59 || parsed.minutes > 59 || parsed.seconds > 59)
      return cancelFinish();
    // package info
    var info = {};
    info.title = titleInput.text
    info.date = Utils.makeDateFromDatestring(str);
    info.description = descriptionInput.text
    root.finished(info);
    console.log(JSON.stringify(info));
  }

  function cancelFinish() {
    dateInput.focusInput();
  }

  function cancelClickedHandler() {
    root.canceld();
  }

  // functions exposed to outside world
  function clear() {
    titleInput.text = "Plan Title";
    var d = new Date();
    dateInput.text = Utils.makeDatestringFromeDate(d);
    descriptionInput.text = "Plan description"
  }

  function setValue(obj) {
    titleInput.text = obj.title;
    dateInput.text = Utils.makeDatestringFromeDate(obj.date);
    descriptionInput.text = obj.description;
  }

  Column {
    width: root.width
    // two buttons
    Item {
      id: btnGrp
      width: root.width
      height: Statics.dialog.btnGrpHeight

      // cancel btn
      Row {
        DialogButton {
          width: btnGrp.width / 2
          height: btnGrp.height
          text: "取消"
          btnColor: Statics.pallete.primary
          onClicked: cancelClickedHandler()
        }

        DialogButton {
          width: btnGrp.width / 2
          height: btnGrp.height
          text: "完成"
          btnColor: Statics.pallete.success
          onClicked: finClickedHandler()
        }
      }
    }
    // end btnGrp

    DialogInput {
      id: titleInput
      label: "标题"
      width: root.width
      height: Statics.dialog.titleInputHeight
    }

    DialogInput {
      id: dateInput
      label: "日期"
      inputMask: "0000-00-00 00:00:00"
      width: root.width
      height: Statics.dialog.dateInputHeight
    }

    DialogEdit {
      id: descriptionInput
      label: "描述"
      width: root.width
      height: Statics.dialog.descriptionInputHeight
    }
  }
}

